import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'     // 第1处修改，删除不必要的导包

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
const whiteList = ['/login', '/auth-redirect', '/bind', '/register'] // 第2处修改，增加白名单

// router.beforeEach(async(to, from, next) => {
router.beforeEach((to, from, next) => { // 第3处修改，去掉“async”，async表示异步进行，去掉后以下代码按顺序进行
    // start progress bar
    NProgress.start()

    // set page title
    // document.title = getPageTitle(to.meta.title)     // 第4处修改，原方法为“根据不同路由设置动态标题”，本项目不使用

    // determine whether the user has logged in
    // const hasToken = getToken()     // 第5处修改，不需要定义常量，直接使用

    // if (hasToken) {
    //   if (to.path === '/login') {
    //     // if is logged in, redirect to the home page
    //     next({ path: '/' })
    //     NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    //   } else {
    //     // determine whether the user has obtained his permission roles through getInfo
    //     const hasRoles = store.getters.roles && store.getters.roles.length > 0
    //     if (hasRoles) {
    //       next()
    //     } else {
    //       try {
    //         // get user info
    //         // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
    //         const { roles } = await store.dispatch('user/getInfo')

    //         // generate accessible routes map based on roles
    //         const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

    //         // dynamically add accessible routes
    //         router.addRoutes(accessRoutes)

    //         // hack method to ensure that addRoutes is complete
    //         // set the replace: true, so the navigation will not leave a history record
    //         next({ ...to, replace: true })
    //       } catch (error) {
    //         // remove token and go to login page to re-login
    //         await store.dispatch('user/resetToken')
    //         Message.error(error || 'Has Error')
    //         next(`/login?redirect=${to.path}`)
    //         NProgress.done()
    //       }
    //     }
    //   }
    // } else {
    //   /* has no token*/

    //   if (whiteList.indexOf(to.path) !== -1) {
    //     // in the free login whitelist, go directly
    //     next()
    //   } else {
    //     // other pages that do not have permission to access are redirected to the login page.
    //     next(`/login?redirect=${to.path}`)
    //     NProgress.done()
    //   }
    // }
    if (getToken()) { // 第6处修改，改写整个判断逻辑顺序
        /* has token*/
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            if (store.getters.roles.length === 0) {
                // 判断当前用户是否已拉取完user_info信息
                store.dispatch('user/getInfo').then(res => {
                        // 拉取user_info
                        const roles = res.roles
                        store.dispatch('generateRoutes', { roles }).then(accessRoutes => {
                            // 测试 默认静态页面
                            // store.dispatch('permission/generateRoutes', { roles }).then(accessRoutes => {
                            // 根据roles权限生成可访问的路由表
                            router.addRoutes(accessRoutes) // 动态添加可访问路由表
                            next({...to, replace: true }) // hack方法 确保addRoutes已完成
                        })
                    })
                    .catch(err => {
                        store.dispatch('user/fedLogOut').then(() => {
                            Message.error(err)
                            next({ path: '/' })
                        })
                    })
            } else {
                // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
                next()
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})